#!/usr/bin/python3
# -*- coding: utf-8 -*-

from pathlib import Path

from sqlalchemy import REAL, Column, Integer, Text, create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

from constant.constants import DataBase
from public.project_patch import DB
from utils.log import log

Base = declarative_base()


class ApiRequest(Base):
    """
    请求表
    """

    __tablename__ = DataBase.API_REQUEST_TABLE

    id = Column(Integer, autoincrement=True, primary_key=True)
    action = Column(Text())
    request_time = Column(Text())
    host = Column(Text())
    url = Column(Text())
    method = Column(Text())
    headers = Column(Text())
    body = Column(Text())

    def __repr__(self) -> str:
        return (
            f"<ApiRequest(id={self.id},"
            f"action={self.action},"
            f"request_time={self.request_time},"
            f"host={self.host},"
            f"url={self.url},"
            f"method={self.method},"
            f"headers={self.headers},"
            f"body={self.body},)>"
        )


class ApiResponse(Base):
    """
    响应表
    """

    __tablename__ = DataBase.API_RESPONSE_TABLE

    id = Column(Integer, autoincrement=True, primary_key=True)
    action = Column(Text())
    response_time = Column(Text())
    host = Column(Text())
    url = Column(Text())
    headers = Column(Text())
    response = Column(Text())
    status_code = Column(Integer())

    def __repr__(self) -> str:
        return (
            f"<ApiResponse(id={self.id},"
            f"action={self.action},"
            f"response_time={self.response_time},"
            f"host={self.host},"
            f"url={self.url},"
            f"headers={self.headers},"
            f"response={self.response},"
            f"status_code={self.status_code})>"
        )


class Config(Base):
    """
    配置表
    """

    __tablename__ = DataBase.CONFIG_TABLE

    key = Column(Text(), primary_key=True)
    value = Column(Text())

    def __repr__(self) -> str:
        return f"<Config(key={self.key}," f"value={self.value})>"


class TestCases(Base):
    """
    测试用例表
    """

    __tablename__ = DataBase.TEST_CASES_TABLE

    id = Column(Integer, autoincrement=True, primary_key=True)
    case_name = Column(Text())
    class_name = Column(Text())
    test_status = Column(Text())
    test_case_path = Column(Text())
    description = Column(Text())

    def __repr__(self) -> str:
        return (
            f"<TestCases(id={self.id},"
            f"case_name={self.case_name}>,"
            f"class_name={self.class_name},"
            f"test_status={self.test_status},"
            f"test_case_path={self.test_case_path},"
            f"description={self.description})>"
        )


class SqliteSqlalchemy:
    """
    eg:
    session = SqliteSqlalchemy('./database/pitrix.db').session
    schema = Schema(api_name='TYW',schema='TEST')
    session.add(schema)
    session.commit()
    """

    def __init__(self, pitrix_db_path):
        engine = create_engine(f"sqlite:///{pitrix_db_path}", echo=True)
        Base.metadata.create_all(engine)
        self.session = sessionmaker(bind=engine)()


def create_tables(pitrix_db_path):
    """
    创建数据表
    @return:
    """
    try:
        engine = create_engine(f"sqlite:///{pitrix_db_path}")
        Session = sessionmaker()
        Session.configure(bind=engine)
        session = Session()
        Base.metadata.create_all(engine)
        log.info(f"创建数据库:{pitrix_db_path} 完成")
    except Exception as e:
        log.info(f"创建数据库:{pitrix_db_path} 失败，str{e}")


def delete_db(pitrix_db_path):
    """
    删除数据库
    :param pitrix_db_path:
    :return:
    """
    path = Path(pitrix_db_path)
    if path.exists():
        path.unlink()
        log.info(f"数据库文件: {pitrix_db_path}删除成功")
    else:
        log.info("数据库文不存在")


if __name__ == "__main__":
    create_tables(DB)
